/**
  * @description: g2--双饼图（左/右）
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, { Component } from 'react';
import G2 from '@antv/g2';
import DataSet from '@antv/data-set';
import { getMediaById } from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';

 
@inject('chartStore') 
@observer


class PieDoubleChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: '',
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            haveData: false,

            groupTitle: [],
            legend: 'top',

            dataNullLeft: false, // 左边图例暂无数据
            dataNullRight: false, // 右边图例暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            pageInitFlag: true,
            affectName: '',
            requireCondition: '',
        };
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false
                        })
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }

    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item);
                    })
                }
            })
        }
    }


    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                this.setState({
                    title: str.data.doubleChartTitle
                })

                // 数据处理
                this.handleData(str.data);
            } else {
                this.setState({
                    dataNullLeft: true,
                    dataNullRight: true
                })
            }
        } else {
            this.setState({
                dataNullLeft: true,
                dataNullRight: true
            })
        }
    }
    // 数据处理
    handleData = (allData) => {
        let storeAllData = allData.data.slice();
        this.setState({
            dataNullLeft: true,
            dataNullRight: true
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (allData.affect && allData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: allData.doubleChartTitle ? allData.doubleChartTitle : '',
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                allData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (allData.requires && allData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: allData.doubleChartTitle ? allData.doubleChartTitle : '',
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                allData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (allData.affect &&  allData.affect.length > 0) {
                this.setState({
                    affectName: allData.affect[0]
                });
            }
            // 获取选择项
            if (allData.conditionValues) {
                let selectData = allData.conditionValues[allData.affect[0]] ? allData.conditionValues[allData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }



        let groupTitle = [];
        storeAllData.map((item,index) => {
            groupTitle.push(item.title);
        })

        this.setState({
            groupTitle: groupTitle
        })

        if (storeAllData.length > 0) {
            document.getElementById('chart_'+this.state.id+'_'+this.state.chartId+'_left').innerHTML = '';
            document.getElementById('chart_'+this.state.id+'_'+this.state.chartId+'_right').innerHTML = '';
            storeAllData.map((item,index) => {
                if (index == 0) {
                    this.setState({
                        dataNullLeft: false
                    })
                } else if (index == 1) {
                    this.setState({
                        dataNullRight: false
                    })
                }
            
                let domId = index == 0 ? 'chart_'+this.state.id+'_'+this.state.chartId+'_left' : 'chart_'+this.state.id+'_'+this.state.chartId+'_right';
                if (item.chartType == 'BasicPieChart') {
                    this.renderBasicPie(item,domId);
                } else if (item.chartType == 'PieHollowChart') {
                    this.renderHollowPie(item,domId);
                } else if (item.chartType == 'PieChart') {
                    this.renderPie(item,domId);
                }
            })
        }
    }


    // 渲染双层饼图
    renderBasicPie = (storeData,domId) => {
        const _this = this;

        // 组装当前图例的维度和度量
        let xyArr = [];
        Object.keys(storeData.columnMaps).forEach(function(key){
            xyArr.push(key)
        });
        let colorArrInner = storeData.colors.split(']')[0].split('[')[1].split(',');
        let colorArrOut = storeData.colors.split(']')[1].split('[')[1].split(',');
        let data = storeData.data.slice();
        let innerX = storeData.innerDimension;
        let outX = storeData.outerDimension;
        let y = storeData.outerField;
        
        if (data.length > 0) {
            this.setState({
                dataNullLeft: false
            })

            // 通过 DataSet 计算百分比
            // let dv = new DataView();
            let ds = new DataSet();
            let dv = ds.createView();
            dv.source(data).transform({
                type: 'percent',
                field: y,
                dimension: innerX,
                as: 'percent'
            });
            let chartLeft = new G2.Chart({
                container: domId,
                forceFit: true,
                height: _this.state.height - 50,
                padding:  storeData.padding && storeData.padding != '' ? storeData.padding.split(',') : [0,90,50,0], // 默认legend在right-top位置,
            });
            chartLeft.source(dv, {
                percent: {
                formatter: function formatter(val) {
                    val = (val * 100).toFixed(2) + '%';
                    return val;
                }
                }
            });
            chartLeft.coord('theta', {
                radius: 0.43
            });
            chartLeft.tooltip({
                // triggerOn: 'click',
                title: 'time_range',
                useHtml:true,
                htmlContent:function(title,items){
                    let itemContnt = '';
                    items.map((v,i) => {
                        itemContnt += '<li style="display: block;" style="padding-left: 5px;">'
                                        + '<span style="background-color:'+  v.color +';width: 6px;height: 6px;display: inline-block;border-radius: 3px;margin-right: 3px;" class="g2-tooltip-marker"></span>'
                                        + '<span style="color: #BDE9FF;">'+  v.name +'： </span>'
                                        + '<span style="color: '+  v.color +';">'+  v.value +'</span>'
                                + '</li>';
                    })
                    return '<div class="g2-tooltip" style="padding: 5px 15px 15px 10px;position: absolute;left: '+ items[0].x +';top:'+  items[0].y +';">'
                            + '<div class="g2-tooltip-title" style="margin-bottom: 4px;color: #6AEBFC;margin-top: 7px;">'+ title +'</div>'
                            + '<ul class="g2-tooltip-list">'
                                + itemContnt
                            + '</ul>'
                        + '</div>';
                }
            });
            chartLeft.legend({
                position: storeData.legend ? storeData.legend : 'right-top',
                offsetX: -15,
                marker: 'square',
                textStyle: {
                    fill: '#24C6F5', // 文本的颜色
                    fontSize: '12', // 文本大小
                },
            });
            chartLeft.intervalStack().position('percent').color(innerX,colorArrInner).label(innerX, {
                offset: -10
            }).tooltip(innerX+'*percent', function(item, percent) {
                percent = (percent * 100).toFixed(2) + '%';
                return {
                    name: item,
                    value: percent
                };
            });


            let outterView = chartLeft.view();
            // let dv1 = new DataView();
            let dv1 = ds.createView();;
            dv1.source(data).transform({
                type: 'percent',
                field: y,
                dimension: outX,
                as: 'percent'
            });
            outterView.source(dv1, {
                percent: {
                formatter: function formatter(val) {
                    val = (val * 100).toFixed(2) + '%';
                    return val;
                }
                }
            });
            outterView.coord('theta', {
                innerRadius: 0.49 / 0.67,
                radius: 0.67
            });
            outterView.intervalStack().position('percent').color(outX, colorArrOut)
            .tooltip(outX+'*percent', function(item, percent) {
                percent = (percent * 100).toFixed(2) + '%';
                return {
                    name: item,
                    value: percent
                };
            });
            

            chartLeft.render();
        }
    }
    // 渲染实心饼图
    renderPie = (storeData,domId) => {
        const _this = this;

        // 组装当前图例的维度和度量
        let xyArr = [];
        Object.keys(storeData.columnMaps).forEach(function(key){
            xyArr.push(key)
        });
        let colorArr = storeData.colors.split(',');
        let data = storeData.data.slice();
        let x = storeData.field;
        let y = storeData.dimension;

        if (data.length > 0) {
            this.setState({
                dataNullLeft: false
            })

            let chartLeft = new G2.Chart({
                container: domId,
                forceFit: true,
                height: _this.state.height - 50,
                padding:  storeData.padding && storeData.padding != '' ? storeData.padding.split(',') : [0,90,50,0], // 默认legend在right-top位置,
                animate: false
            });
            chartLeft.source(data);
            chartLeft.tooltip(false);
            chartLeft.legend({
                position: storeData.legend ? storeData.legend : 'right-top',
                offsetX: 0,
                // offsetY: 20,
                marker: 'square',
                // itemWidth: 70,
                // itemGap: 20, // 表示图例每项之间的间距，如果是水平排布则为左右间距，如果是竖直排布则为上下间距。
                textStyle: {
                    fill: '#fff', // 文本的颜色
                    fontSize: '12', // 文本大小
                },
            });
            chartLeft.coord('theta', {
                radius: 0.67
            });
            chartLeft.tooltip({
                triggerOn: 'click',
                title: 'time_range',
                useHtml:true,
                htmlContent:function(title,items){
                    let itemContnt = '';
                    items.map((v,i) => {
                        itemContnt += '<li style="display: block;" style="padding-left: 5px;">'
                                        + '<span style="background-color:'+  v.color +';width: 6px;height: 6px;display: inline-block;border-radius: 3px;margin-right: 3px;" class="g2-tooltip-marker"></span>' 
                                        + '<span style="color: #BDE9FF;">'+  v.name +'： </span>'
                                        + '<span style="color: '+  v.color +';">'+  v.value +'</span>'
                                + '</li>';
                    })
                    return '<div class="g2-tooltip" style="padding: 5px 15px 15px 15px;position: absolute;left: '+ items[0].x +';top:'+  items[0].y +';">' 
                            + '<div class="g2-tooltip-title" style="margin-bottom: 4px;color: #6AEBFC;margin-top: 7px;">'+ title +'</div>'
                            + '<ul class="g2-tooltip-list">'
                                + itemContnt
                            + '</ul>'
                        + '</div>';
                }
            });

            chartLeft.intervalStack().position(y).color(x,colorArr).opacity(1).label(y, {
                offset: -18,
                textStyle: {
                    fill: 'white',
                    fontSize: 12,
                    shadowBlur: 2,
                    shadowColor: 'rgba(0, 0, 0, .45)'
                },
                rotate: 0,
                autoRotate: false,
                formatter: function formatter(text, item) {
                //return String(parseInt(item.point.percent * 100)) + '%';
                }
            });
            chartLeft.render();

        }
    }
    // 渲染空心饼图
    renderHollowPie = (storeData,domId) => {
        const _this = this;

        // 组装当前图例的维度和度量
        let xyArr = [];
        Object.keys(storeData.columnMaps).forEach(function(key){
            xyArr.push(key)
        });
        let colorArr = storeData.colors.split(',');
        let data = storeData.data.slice();
        let x = storeData.field;
        let y = storeData.dimension;

        if (data.length > 0) {
            this.setState({
                dataNullRight: false
            })

        
            // 图例渲染
            let ds = new DataSet();
            let dv = ds.createView().source(data);

            let chartLeft = new G2.Chart({
                container: domId,
                forceFit: true,
                height: _this.state.height - 50,
                padding:  storeData.padding && storeData.padding != '' ? storeData.padding.split(',') : [0,90,50,0], // 默认legend在right-top位置,
                animate: false
            });
            chartLeft.source(dv);
            chartLeft.coord('theta', {
                radius: 0.67,
                innerRadius: 0.66
            });
            chartLeft.legend({
                position: storeData.legend ? storeData.legend : 'right-top',
                offsetX: -15,
                marker: 'square',
                textStyle: {
                    fill: '#24C6F5', // 文本的颜色
                    fontSize: '12', // 文本大小
                },
            });
            chartLeft.tooltip(false);
            // chartLeft.tooltip({
            //     triggerOn: 'click',
            //     // title: 'time_range',
            //     useHtml:true,
            //     htmlContent:function(title,items){
            //         let itemContnt = '';
            //         items.map((v,i) => {
            //             itemContnt += '<li style="display: block;" style="padding-left: 5px;">'
            //                             + '<span style="background-color:'+  v.color +';width: 6px;height: 6px;display: inline-block;border-radius: 3px;margin-right: 3px;" class="g2-tooltip-marker"></span>'
            //                             + '<span style="color: #BDE9FF;">'+  v.name +'： </span>'
            //                             + '<span style="color: '+  v.color +';">'+  v.value +'</span>'
            //                     + '</li>';
            //         })
            //         return '<div class="g2-tooltip" style="padding: 5px 15px 15px 10px;background: url('+require('./images/pieDouble-tooltip-bg.png')+') no-repeat;background-size: 100% 100%;position: absolute;left: '+ items[0].x +';top:'+  items[0].y +';">'
            //                 + '<div class="g2-tooltip-title" style="margin-bottom: 4px;color: #6AEBFC;margin-top: 7px;">'+ '' +'</div>'
            //                 + '<ul class="g2-tooltip-list">'
            //                     + itemContnt
            //                 + '</ul>'
            //             + '</div>';
            //     }
            // });

            let interval = chartLeft.intervalStack().position(y).color(x,colorArr).tooltip(x+'*'+y, function(item, percent) {
                return {
                    name: item,
                    value: percent
                };
            });
            // 辅助文本
            chartLeft.guide().html({
                position: ['50%', '50%'],
                html: '<div id="g2-guide-html" style="width: 10em;height: 3em;text-align: center;line-height: 0.2;">'+
                        '<p id="pie-center-title" style="font-size: 12px;color: #26D3FA;font-weight: 300;margin: 0;">'+ data[0][x]+'</p>'+
                        '<p id="pie-center-value" style="font-size: 24px;color: #97FAFF;font-weight: bold;;margin: 0;font-family: myNumberFamily;">'+ data[0][y]+'</p>'+
                        '</div>', 
            });
            
            chartLeft.on('interval:click', function(ev) {
                let data = ev.data._origin;
                document.getElementById('g2-guide-html').style.opacity = 1;
                document.getElementById('pie-center-title').innerText = data[x];
                document.getElementById('pie-center-value').innerText = data[y];
            });
            chartLeft.render();
            interval.setSelected(dv.origin[0]);
        }
    }


    // 改变全局变量
    onGlobalVariable = (val) => {
        const { saveAffectId } = this.props.chartStore;
        saveAffectId(this.state.chartId);
        this.props.onGlobalVariable(val);
    }

    


    render() {
        const _this = this;
        let Layer = this.props.layer;

        let chartData = this.state.chartData;
        let axisArr = this.state.axisArr;
        let haveData = this.state.haveData;
        let x = this.state.dimension;
        let y1 = this.state.field;
        let y2 = axisArr[2];

        if (haveData && chartData.length > 0) {
            _this.setState({
                haveData: false
            })
        }

        return (
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 99,width: this.state.width,height: this.state.height,padding: '40px 2% 10px 2%'}}>
                <Layer width={this.state.width} title={this.state.title} groupTitle={this.state.groupTitle} chartId={this.state.chartId} choiceData={this.state.mainData} onGlobalVariable={this.onGlobalVariable}></Layer>
                <div id={'chart_'+this.state.id+'_'+this.state.chartId}>
                    <div id={'chart_'+this.state.id+'_'+this.state.chartId+'_left'} style={{display: 'inline-block',float: 'left',width: '44%',height: '100%',marginLeft: '2%'}}></div>
                    { this.state.dataNullLeft && <p style={{display: 'inline-block',float: 'left',width: '44%',height: this.state.height,lineHeight: this.state.height+'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>}
                    <div id={'chart_'+this.state.id+'_'+this.state.chartId+'_right'} style={{display: 'inline-block',float: 'right',width: '44%',height: '100%',marginRight: '2%'}}></div>
                    { this.state.dataNullRight && <p style={{display: 'inline-block',float: 'right',width: '44%',height: this.state.height,lineHeight: this.state.height+'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>}
                </div>
            </div>
        )
    }


}
export default PieDoubleChart;

